<?php
namespace console\models\modules;

use common\models\Common;

class ModuleActions extends Common {
    
    public static function tableName()
    {
        return "{{%module_actions}}";
    }
    
    public function initActions() {
        #拿到cms的路由文件
        $file = \Yii::getAlias("@cms/config/rules.php");
    
        $routes = require $file;
        $i = 1;
        foreach ($routes["rules"] as $v) {
            $c = $this->_getPathAndController($v['controller']);
            $a = $this->_getActions($v['extraPatterns']);
            
            foreach ($a as $vv) {
                $insert = [
                    "method" => strtolower($vv['method']),
                    "controller" => strtolower($c['controller']),
                    "action" => strtolower($vv['action']),
                ];
                
                $check = static::getOneByWhere($insert);
                if (empty($check)) {
                    $insert['id'] = $i;
                    $insert["create_time"] = date("Y-m-d H:i:s");
                    static::insertData($insert);
                } else {
                    static::updateData($insert, ['id' => $check['id']]);
                }
                $i ++;
            }
        }
    }
    
    private function _getPathAndController($controller = '') {
        $a = explode('/', $controller);
        
        return ['version' => $a[0], "controller" => $a[1]];
    }
    
    private function _getActions($extraPatterns = []) {
        $result = [];
        foreach ($extraPatterns as $k => $v) {
            $kk = explode(" ", $k);
            $methods = $kk[0];
            $methodsArr = explode(",", $methods);
            foreach ($methodsArr as $vv) {
                if (strtolower($vv) == "options") {
                    continue;
                }
                $tmp = [
                    "method" => $vv,
                    "action" => $v,
                ];
            }
            $result[] = $tmp;
        }
        
        return $result;
    }
}